<template slot-scope="scope">
  <el-container class="whole">
    <div class="xuanfu" v-if="survey.deadline !== undefined">
      <div class="bar_btn"><i class="el-icon-time"></i>倒计时</div>
      <div class="bar_btn" style="font-size: 18px">
        <span v-if="hour > 0"> {{ hour }}时</span>
        <span v-if="minute > 0">{{ minute }}分</span>{{ second }}秒
      </div>
    </div>
    <el-header
      height="50px"
      style="
        background-color: #313131;
        color: white;
        font-size: 30px;
        line-height: 50px;
      "
      >求索问卷--吾将上下而求索</el-header
    >
    <el-main class="body" v-if="isLock === false">
      <div class="qrcode">
        <vue-qr :text="link" :size="70" :margin="5"></vue-qr>
      </div>
      <div class="date">
        <div>发布者: {{ survey.author }}</div>
        <div>发布时间: {{ pulishTime }}</div>
        <div v-if="survey.deadline !== undefined">
          截止时间: {{ deadlineTime }}
        </div>
      </div>
      <div class="title">{{ survey.title }}</div>
      <div class="description">{{ survey.description }}</div>
      <div v-if="finish === false">
        <div
          v-for="(item, index) in survey.questions"
          :key="index"
          style="border-top: 1px solid #e0e0e0; padding-bottom: 15px"
        >
          <div
            style="
              margin: 0 auto;
              width: 80%;
              padding-top: 30px;
              padding-bottom: 10px;
            "
          >
            <span v-if="!survey.numHidden">第 {{ index + 1 }} 题 </span>(<span
              v-if="item.type === 0"
              >单选</span
            >
            <span v-if="item.type === 1">多选</span>
            <span v-if="item.type === 3">填空</span>
            <span v-if="[1].indexOf(item.type) >= 0"
              ><span v-if="item.propJson.min == item.propJson.max">{{
                item.propJson.min
              }}</span
              ><span v-else
                >{{ item.propJson.min }}~{{ item.propJson.max }}</span
              >个</span
            >)<span v-if="[0, 1].indexOf(item.type) >= 0"
              >({{ scoreInfo[item.num] }}分)</span
            >
            <span v-if="item.required === true" style="color: red">(必选)</span>
          </div>
          <div class="questions">{{ item.stem }}</div>
          <div
            class="questions_description"
            style="color: #999999; font-size: 10px"
          >
            {{ item.description }}
          </div>
          <div v-if="item.type === 0" class="questions">
            <el-radio-group v-model="answer['' + item.num]">
              <el-radio
                v-for="(choice, choice_index) in item.propJson.options"
                :key="choice_index"
                style="display: block; margin: 25px 0"
                :label="choice_index"
                >{{ item.propJson.options[choice_index] }}</el-radio
              >
            </el-radio-group>
          </div>
          <div v-if="item.type === 1" class="questions">
            <el-checkbox-group v-model="answer['' + item.num]">
              <el-checkbox
                v-for="(choice, choice_index) in item.propJson.options"
                :key="choice_index"
                style="display: block; margin: 25px 0"
                :label="choice_index"
                >{{ item.propJson.options[choice_index] }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="item.type === 3" class="questions">
            <el-input
              v-model="answer['' + item.num]"
              type="textarea"
              autosize
              placeholder="在这里填写回答..."
              style="margin: 25px 0"
            ></el-input>
          </div>
        </div>
        <div style="text-align: center; padding: 30px 0">
          <el-button type="primary" @click="check" style="width: 120px"
            >提 交</el-button
          >
        </div>
      </div>
      <div v-else>
        <div
          style="
            text-align: center;
            font-size: 30px;
            margin-top: 130px;
            margin-bottom: 20px;
          "
        >
          你的得分为{{ score }}(客观题总分为{{ totalScore }})
        </div>
        <div style="text-align: center">
          <el-button @click="toMainpage" style="width: 120px">主 页</el-button>
        </div>
      </div>
    </el-main>
    <el-dialog
      :visible.sync="isLock"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="提示"
    >
      <div style="font-size: 20px; line-height: 40px">
        该试卷为非公开试卷,请输入口令后填写 :
      </div>
      <el-input v-model="password" type="password"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="unlock" @keyup.enter.native="unlock"
          >确 认</el-button
        >
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      pulishTime: "",
      deadlineTime: "",
      link: "",
      hour: "",
      minute: "",
      second: "",
      score: "",
      totalScore: 0,
      isLock: false,
      finish: false,
      password: "",
      sid: "",
      scoreInfo: {},
      survey: {},
      answer: {},
    };
  },
  methods: {
    unlock() {
      this.$http
        .get("/survey/" + this.sid + "?code=" + this.password)
        .then((res) => {
          this.answer = this.outputAnswerSheet(this.clone(res.data.questions));
          this.survey = this.clone(res.data);
          // console.log(this.survey);
          for (var i = 0; i < this.survey.questions.length; i++) {
            this.survey.questions[i].propJson = JSON.parse(
              this.survey.questions[i].propJson
            );
          }
          if (this.survey.mixed)
            //打乱顺序
            this.survey.questions = this.mixed(this.survey.questions);
          if (this.survey.deadline !== undefined)
            this.deadlineTime = this.convertTime(this.survey.deadline);
          this.pulishTime = this.convertTime(this.survey.pubTime);
          this.deadlineTime = this.convertTime(this.survey.deadline);
          if (this.survey.deadline !== undefined) this.countTime();
          this.isLock = false;
        })
        .catch((err) => {
          if (err.response.status == 406) {
            alert("口令错误!");
            this.password = "";
          } else {
            alert("网络错误,请稍后再试!");
            this.$router.push("/introduction");
          }
        });
    },
    outputAnswerSheet(questions) {
      var answerSheet = {};
      for (var i = 0; i < questions.length; i++) {
        if ([1, 4, 5, 6].indexOf(questions[i].type) >= 0) {
          answerSheet["" + questions[i].num] = [];
        } else if (questions[i].type === 0) {
          answerSheet["" + questions[i].num] = null;
        } else if (questions[i].type == 2) {
          answerSheet["" + questions[i].num] = 0;
        } else if (questions[i].type == 3) {
          answerSheet["" + questions[i].num] = null;
        }
      }
      return answerSheet;
    },
    check() {
      var unfinish = [];
      var overmax = [];
      var belowmin = [];
      var q = this.survey.questions;
      for (var i = 0; i < q.length; i++) {
        if (q[i].type == 0 && q[i].required && this.answer[q[i].num] == null)
          unfinish.push(i + 1);
        else if (q[i].type == 2 && q[i].required && this.answer[q[i].num] == 0)
          unfinish.push(i + 1);
        else if (q[i].type == 3 && q[i].required && !this.answer[q[i].num])
          unfinish.push(i + 1);
        else if (
          [1, 4, 5, 6].indexOf(q[i].type) >= 0 &&
          q[i].required &&
          this.answer[q[i].num].length == 0
        )
          unfinish.push(i + 1);
        else if ([1, 4, 5].indexOf(q[i].type) >= 0 && q[i].required) {
          if (this.answer[q[i].num].length > q[i].propJson.max) {
            overmax.push(i + 1);
          } else if (this.answer[q[i].num].length < q[i].propJson.min) {
            belowmin.push(i + 1);
          }
        }
      }
      if (unfinish.length > 0 || overmax.length > 0 || belowmin.length > 0) {
        var str = "";
        if (unfinish.length > 0)
          str += "必选题有第" + unfinish.toString() + "题未填写!";
        if (overmax.length > 0)
          str += "第" + overmax.toString() + "题多选题选项个数超过要求个数!";
        if (belowmin.length > 0)
          str += "第" + belowmin.toString() + "题多选题选项个数少于要求个数!";
        alert(str);
      } else {
        // alert(JSON.stringify(this.answer));
        // console.log(encodeURI(JSON.stringify(this.answer)));
        this.submit();
        //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.获取得分
      }
    },
    submit() {
      this.$http
        .post(
          "/survey/ans/exam?sid=" +
            this.sid +
            "&answerJson=" +
            encodeURI(JSON.stringify(this.answer))
          //  +
          // "&uid=" +
          // window.sessionStorage.getItem("uid")
        )
        .then((res) => {
          // console.log(res);
          this.score = res.data.total;
          //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
          this.finish = true;
        })
        .catch((err) => {
          if (err.response.status == 403) {
            alert("问卷未开放或已截止!");
          } else if (err.response.status === 406) {
            alert("你已提交过本试卷了,请勿重复提交!");
          } else {
            alert("网络错误,请稍后再试!");
          }
        });
    },
    convertTime(timestampe) {
      var time = new Date(timestampe);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return (
        y +
        "-" +
        this.add0(m) +
        "-" +
        this.add0(d) +
        "-" +
        this.add0(h) +
        ":" +
        this.add0(mm) +
        ":" +
        this.add0(s)
      );
    },
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    toMainpage() {
      this.$router.push("/introduction");
    },
    clone(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
    countTime() {
      var now = new Date();
      //设置截止时间
      var end = this.survey.deadline;
      //获取截止时间和当前时间的时间差
      var leftTime = end - now;
      //定义变量 d,h,m,s分别保存天数，小时，分钟，秒
      var h, m, s;
      //判断剩余天数，时，分，秒
      if (leftTime >= 500) {
        h = Math.floor(leftTime / 1000 / 60 / 60);
        m = Math.floor((leftTime / 1000 / 60) % 60);
        s = Math.floor((leftTime / 1000) % 60);
      } else {
        //>>>>>>>>>>>>>>>>>>>自动提交试卷
        this.submit();
        return;
      }
      //将时间赋值到div中
      this.hour = this.add0(h);
      this.minute = this.add0(m);
      this.second = this.add0(s);
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(this.countTime, 1000);
    },
    mixed(arr) {
      for (var i = 0; i < arr.length; i++) {
        var iRand = parseInt(arr.length * Math.random());
        var temp = arr[i];
        arr[i] = arr[iRand];
        arr[iRand] = temp;
      }
      return arr;
    },
    getScoreInfo() {
      this.$http
        .get("/survey/ans/exam/score?sid=" + this.sid)
        .then((res) => {
          this.scoreInfo = this.clone(res.data);
          for (var key in this.scoreInfo) {
            this.totalScore += this.scoreInfo[key];
          }
        })
        .catch((err) => {
          if (err.response.status === 401) {
            this.$message.error("用户未登录!");
            this.$router.push("/login");
          } else {
            this.$message.error("网络错误,请稍后再试!");
            this.$router.push("/introduction");
          }
        });
    },
  },
  created() {
    if (this.$store.state.isLogin == false) {
      alert("填写考试问卷需要登录,请登陆后进行填写!");
      this.$router.push("/login");
      return;
    }
    var id = this.$route.params.id;
    this.sid = id;
    this.link = "http://106.12.141.103:8080/index.html#/exam/" + this.sid;
    this.getScoreInfo();
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>后台获取问卷信息
    this.survey = {
      author: "测试人员",
      title: "测试问卷",
      description: "这是描述",
      code: "",
      creTime: 1629539507000,
      pubTime: 1629539626000,
      deadline: 1630403611000,
      status: 1,
      ansNum: 0,
      questions: [
        {
          type: 3,
          stem: "你觉得北航怎么样?",
          description: "",
          required: false,
          propJson: { num: 1 },
        },
      ],
    };
    this.$http
      .get("/survey/" + id)
      .then((res) => {
        this.answer = this.outputAnswerSheet(this.clone(res.data.questions));
        // console.log(this.answer);
        this.survey = this.clone(res.data);
        // console.log(this.survey);
        for (var i = 0; i < this.survey.questions.length; i++) {
          this.survey.questions[i].propJson = JSON.parse(
            this.survey.questions[i].propJson
          );
        }
        if (this.survey.mixed)
          //打乱问题顺序
          this.survey.questions = this.mixed(this.survey.questions);
        this.pulishTime = this.convertTime(this.survey.pubTime);
        if (this.survey.deadline !== undefined)
          this.deadlineTime = this.convertTime(this.survey.deadline);
        this.pulishTime = this.convertTime(this.survey.pubTime);
        this.deadlineTime = this.convertTime(this.survey.deadline);
        if (this.survey.deadline !== undefined) this.countTime();
        // console.log(this.survey);
      })
      .catch((err) => {
        console.log(err);
        if (err.response.status === 403) {
          alert("本问卷暂未开启或已截止,即将跳转至其他页面...");
          this.$router.push("/introduction");
        } else if (err.response.status === 406) {
          console.log("有密码");
          this.isLock = true;
        } else if (err.response.status === 401) {
          alert("考试问卷需要登录才能填写,请先登录!");
          this.$router.push("/login");
        } else {
          alert("问卷获取失败,请稍后再试!");
          this.$router.push("/introduction");
        }
      });
    // console.log(this.survey);
  },
};
</script>


<style lang="less" scoped>
.whole {
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
}
.body {
  height: 100%;
  width: 50%;
  margin: 0 auto;
  background-color: #fff;
  overflow: auto;
}
.title {
  text-align: center;
  padding: 30px 0 20px 0;
  font-size: 30px;
  max-width: 40%;
  margin: 0 auto;
}
.qrcode {
  float: left;
}
.date {
  float: right;
  font-size: 12px;
  padding-right: 10px;
  padding-top: 10px;
  color: #5a5a5a;
}
.description {
  text-align: center;
  font-size: 15px;
  max-width: 60%;
  margin: 0 auto;
  padding-bottom: 20px;
}
.questions {
  width: 80%;
  margin: 0 auto;
}
.questions_description {
  width: 80%;
  margin: 5px auto;
}
.xuanfu {
  width: 150px;
  position: fixed;
  left: 150px;
  top: 150px;
  z-index: 1100;
}
.bar_btn {
  width: 100%;
  height: 50px;
  font-size: 19px;
  color: #606266;
  line-height: 50px;
  border: 2px solid #dcdfe6;
  text-align: center;
  border-radius: 5px;
  user-select: none;
  background-color: #fff;
}
</style>